package com.zx.cashiersystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zx.cashiersystem.cashiersystem.R;
import com.zx.cashiersystem.device.PrinterSample;
import com.zx.cashiersystem.entitys.AliPayFacePayBean;
import com.zx.cashiersystem.entitys.AliPayQrPayBean;
import com.zx.cashiersystem.entitys.OrderInfo;
import com.zx.cashiersystem.entitys.WxPayBean;
import com.zx.cashiersystem.entitys.WxQrPayBean;
import com.zx.cashiersystem.mvp.model.OnResultListener;
import com.zx.cashiersystem.utils.ArithmeticUtils;
import com.zx.cashiersystem.utils.CashierInputFilter;
import com.zx.cashiersystem.utils.Contants;
import com.zx.cashiersystem.utils.ContantsIntent;
import com.zx.cashiersystem.utils.DiscountPay;
import com.zx.cashiersystem.utils.PayUtil;
import com.zx.cashiersystem.utils.Toasts;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/13.
 * <p>
 * 支付页面--不包含优惠页面
 */

public class PayActivity extends BaseActivity implements View.OnClickListener, OnResultListener {
    private TextView tvFavorablePay;
    private ImageView ivCashPay;
    private LinearLayout llCombinationPay;
    private ImageView ivCombinationPay1;
    private ImageView ivCombinationPay2;
    private ImageView ivAlipayPay;
    private TextView tvChange;
    private ImageView ivWxpayPay;
    private TextView tvSettlePay;
    private TextView tvQuitPay;
    private ImageView ivCardPay;
    private ImageView ivUnionpayPay;
    private ImageView ivScanPay;
    private EditText etAggregatePay;
    private EditText etIncomePay;
    private EditText etCombinationPay1;
    private EditText etCombinationPay2;
    private EditText etChangePay;
    private CheckBox ckPay;
    private OrderInfo orderInfo;
    public List<View> paylist = new ArrayList();
    private int NUMBER = 1;
    private String TAG1 = "0";
    private String moneyString = "";
    private String discountNum = "";
    private String favorableNum = "";

    //ABOUT PRINT
    private PrinterSample printerSample;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        printerSample = new PrinterSample(this) {

            @Override
            protected void onDeviceServiceCrash() {
                PayActivity.this.onDeviceServiceCrash();
            }

            @Override
            protected void displayPrinterInfo(String info) {
                PayActivity.this.displayInfo(info);
            }
        };
    }

    /**
     * If device service crashed, quit application or try to relogin service again.
     */
    public void onDeviceServiceCrash() {
        bindDeviceService();
    }

    /**
     * All device operation result infomation will be displayed by this method.
     *
     * @param info
     */
    public void displayInfo(String info) {

        //要看什么时间打印log

        Log.d("PayActivity", "print=="+ info);

    }


    @Override
    protected void initView() {
        tvFavorablePay = (TextView) findViewById(R.id.tv_favorable_pay);
        ivCashPay = (ImageView) findViewById(R.id.iv_cash_pay);
        llCombinationPay = (LinearLayout) findViewById(R.id.ll_combination_pay);
        ivCombinationPay1 = (ImageView) findViewById(R.id.iv_combination_pay1);
        ivCombinationPay2 = (ImageView) findViewById(R.id.iv_combination_pay2);
        ivAlipayPay = (ImageView) findViewById(R.id.iv_alipay_pay);
        tvChange = (TextView) findViewById(R.id.tv_change);
        ivWxpayPay = (ImageView) findViewById(R.id.iv_wxpay_pay);
        tvSettlePay = (TextView) findViewById(R.id.tv_settle_pay);
        tvQuitPay = (TextView) findViewById(R.id.tv_quit_pay);
        ivCardPay = (ImageView) findViewById(R.id.iv_card_pay);
        ivUnionpayPay = (ImageView) findViewById(R.id.iv_unionpay_pay);
        ivScanPay = (ImageView) findViewById(R.id.iv_scan_pay);
        etAggregatePay = (EditText) findViewById(R.id.et_aggregate_pay);
        etIncomePay = (EditText) findViewById(R.id.et_income_pay);
        etCombinationPay1 = (EditText) findViewById(R.id.et_combination_pay1);
        etCombinationPay2 = (EditText) findViewById(R.id.et_combination_pay2);
        etChangePay = (EditText) findViewById(R.id.et_change_pay);
        ckPay = (CheckBox) findViewById(R.id.ck_pay);

    }


    @Override
    protected void initEvent() {
        tvFavorablePay.setOnClickListener(this);

        ivCashPay.setOnClickListener(this);
        ivAlipayPay.setOnClickListener(this);
        ivWxpayPay.setOnClickListener(this);
        ivCardPay.setOnClickListener(this);
        ivUnionpayPay.setOnClickListener(this);
        ivScanPay.setOnClickListener(this);
        tvSettlePay.setOnClickListener(this);
        tvQuitPay.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        inputEdit();
        orderInfo = (OrderInfo) getIntent().getSerializableExtra(ContantsIntent.ORDERINFO);
        etAggregatePay.setText(orderInfo.getTotalprice() + "");
        ivCashPay.setSelected(true); //默认现金支付

        paylist.add(ivCashPay);
        paylist.add(ivAlipayPay);
        paylist.add(ivWxpayPay);
        paylist.add(ivCardPay);
        paylist.add(ivUnionpayPay);
        paylist.add(ivScanPay);

    }

    @Override
    protected void onResume() {
        super.onResume();

        unbindDeviceService();
        if (!discountNum.isEmpty() && !orderInfo.getTotalprice().toString().isEmpty()) {
            etAggregatePay.setText(DiscountPay.getZhekou(orderInfo.getTotalprice().toString(), discountNum));
        }
        if (!favorableNum.isEmpty() && !orderInfo.getTotalprice().toString().isEmpty()) {
            etAggregatePay.setText(DiscountPay.getFavorableMoney(orderInfo.getTotalprice().toString(), favorableNum));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_favorable_pay:   //优惠按钮
                startActivityForResult(new Intent(this, DisCountActivity.class), ContantsIntent.DISCOUNTREQUESTCODE);
                break;
            case R.id.iv_cash_pay:  //现金支付图标
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivCashPay.getTag().toString();
                } else {
                    setPays(ivCashPay.getTag().toString());
                }
                break;
            case R.id.iv_alipay_pay:        //支付宝
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivAlipayPay.getTag().toString();
                } else {
                    setPays(ivAlipayPay.getTag().toString());
                }
                break;
            case R.id.iv_wxpay_pay:        //微信
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivWxpayPay.getTag().toString();
                } else {
                    setPays(ivWxpayPay.getTag().toString());
                }
                break;
            case R.id.iv_card_pay:       //储值卡
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivCardPay.getTag().toString();
                } else {
                    setPays(ivCardPay.getTag().toString());
                }
                break;
            case R.id.iv_unionpay_pay:    //银联
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivUnionpayPay.getTag().toString();
                } else {
                    setPays(ivUnionpayPay.getTag().toString());
                }
                break;
            case R.id.iv_scan_pay:    //扫一扫
                selectedSet(String.valueOf(v.getId()), paylist);
                if (NUMBER == 1) {
                    TAG1 = ivScanPay.getTag().toString();
                } else {
                    setPays(ivScanPay.getTag().toString());
                }
                break;
            case R.id.tv_settle_pay:     //结账按钮
                displayInfo(" -----------startPrint------------- ");
                printerSample.startPrint();
                printerSample.addPrintInfo("100元");

                if (ckPay.isChecked()) {        //如果是组合支付
                    Double differMoney = 0.00;
                    if (NUMBER == 1) {  //如果第一次点击

                        //如果收入金额大于或等于总金额,就不进行支付
                        if (!TextUtils.isEmpty(etIncomePay.getText().toString().trim())) {
                            String aggregateMoney = etAggregatePay.getText().toString().trim();
                            String incomeMoney = etIncomePay.getText().toString().trim();
                            if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == 1) {
                                ckPay.setChecked(false);
                                return;
                            } else if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == 0) {
                                ckPay.setChecked(false);
                                return;
                            } else if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == -1) {   //如果收入金额小于应付金额
                                differMoney = Double.valueOf(ArithmeticUtils.sub(aggregateMoney, incomeMoney, 2));
                                getMoney(Double.valueOf(incomeMoney), TAG1); //根据TAG的类型找到相应的支付路径并进行支付
                            }
                            moneyString = etIncomePay.getText().toString().trim();
                            etIncomePay.setVisibility(View.GONE);
                            llCombinationPay.setVisibility(View.VISIBLE);
                            for (int i = 0; i < paylist.size(); i++) {
                                if (TAG1 == paylist.get(i).getTag().toString()) {
                                    ivCombinationPay1.setImageDrawable(((ImageView) paylist.get(i)).getDrawable());
                                }
                            }
                            etCombinationPay1.setText(moneyString);
                            etCombinationPay2.setText(String.valueOf(differMoney));
                            selectedSet(String.valueOf(ivAlipayPay.getId()), paylist);
                            etChangePay.setText("0.00");
                            NUMBER++;
                        }
                    } else {
                        differMoney = Double.valueOf(ArithmeticUtils.sub(etAggregatePay.getText().toString().trim(), etIncomePay.getText().toString().trim(), 2));
                        if (!TextUtils.isEmpty(etCombinationPay2.getText().toString().trim())) {
                            if ((ArithmeticUtils.compare(String.valueOf(differMoney), etCombinationPay2.getText().toString().trim()) == 0)
                                    || (ArithmeticUtils.compare(String.valueOf(differMoney), etCombinationPay2.getText().toString().trim()) == -1)) {
                                getMoney(Double.valueOf(etCombinationPay2.getText().toString().trim()), String.valueOf(ivCombinationPay2.getTag())); //根据TAG的类型找到相应的支付路径并进行支付
                                etChangePay.setText(ArithmeticUtils.sub(etCombinationPay2.getText().toString().trim(), String.valueOf(differMoney), 2));
                            } else {
                                Toasts.showShort(this, "金额不对");
                                return;
                            }
                        }
                        NUMBER = 1;
                    }
                } else {   //没有勾选组合支付的话

                    if (!TextUtils.isEmpty(etIncomePay.getText().toString().trim())) {
                        String aggregateMoney = etAggregatePay.getText().toString().trim();
                        String incomeMoney = etIncomePay.getText().toString().trim();
                        if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == -1) {   //如果收入金额小于应付金额
                            return;
                        }
                        if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == 1) {
                            etChangePay.setText(ArithmeticUtils.sub(incomeMoney, aggregateMoney, 2));
                            getMoney(Double.valueOf(incomeMoney), TAG1); //根据TAG的类型找到相应的支付路径并进行支付
                        }
                        if (ArithmeticUtils.compare(incomeMoney, aggregateMoney) == 0) {
                            etChangePay.setText("0.00");
                            getMoney(Double.valueOf(incomeMoney), TAG1); //根据TAG的类型找到相应的支付路径并进行支付
                        }
                    } else {
                        return;
                    }
                }

                break;
            case R.id.tv_quit_pay:
                finish();  //关闭界面
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == ContantsIntent.DISCOUNTRRESULTCODE) {
            if (requestCode == ContantsIntent.DISCOUNTREQUESTCODE) {
                discountNum = data.getStringExtra(ContantsIntent.DISCOUNTNUM);
                favorableNum = data.getStringExtra(ContantsIntent.FAVORABLENUMBER);
            }
        }
    }

    //根据传入的金额和TAG选择相应的支付方式
    public void getMoney(Double money, String tag) {
        switch (tag) {
            case "1":    //现金支付
                Toasts.showShort(this, "现金" + money);

                break;
            case "2":        //支付宝
                Toasts.showShort(this, "支付宝" + money);


                PayUtil.aliPayFacePay(Contants.ALIPAY_FACEPAY_CODE, context, "22222", "test", money.toString(), "test", this, null);

                break;
            case "3":      //微信
                Toasts.showShort(this, "微信" + money);
                PayUtil.wxPay(Contants.WXPAY_CODE, context, "1" + (int) (1 + Math.random() * (1000000)), "11111", money.toString(), "test", this, null);

                break;
            case "4":     //充值卡
                Toasts.showShort(this, "充值卡" + money);

                break;
            case "5":      //银联
                Toasts.showShort(this, "银联" + money);

                break;
            case "6":         //被扫
                Toasts.showShort(this, "被扫" + money);
//                PayUtil.aliQrPay(Contants.ALIPAY_QRPAY_CODE, context, "1" + (int) (1 + Math.random() * (1000000)), money.toString(), "test", "test", this, null);
//                PayUtil.wxQrPay(Contants.WXQRPAY_CODE, context, "test", "1" + (int) (1 + Math.random() * (1000000)), "e", money.toString(), this, null);
                break;
        }
    }

    //初始化输入框过滤器
    public void inputEdit() {

        //设置收入输入框只能输入金额
        CashierInputFilter[] filter = {new CashierInputFilter()};
        etIncomePay.setFilters(filter);
        etCombinationPay2.setFilters(filter);
    }

    //设置选中状态
    public void selectedSet(String id, List<View> list1) {
        for (int i = 0; i < list1.size(); i++) {
            if (!id.equals(String.valueOf(list1.get(i).getId()))) {
                list1.get(i).setSelected(false);
            } else {
                list1.get(i).setSelected(true);
            }
        }
    }

    //设置第二种支付的图标
    public void setPays(String tag) {
        for (int i = 0; i < paylist.size(); i++) {
            if (tag == paylist.get(i).getTag().toString()) {
                ivCombinationPay2.setImageDrawable(((ImageView) paylist.get(i)).getDrawable());
                ivCombinationPay2.setTag(tag);   //设置标记
            }
        }
    }

    @Override
    public void onSuccess(int requestCode, String str) {
        Log.d("ABOUT PAY=====onSuccess", str);
        switch (requestCode) {
            case Contants.ALIPAY_FACEPAY_CODE:
                AliPayFacePayBean aliPayFacePayBean = JSON.parseObject(str, new TypeReference<AliPayFacePayBean>() {
                });
                Toasts.show(context, aliPayFacePayBean.getMsg());
                break;
            case Contants.ALIPAY_QRPAY_CODE:

                AliPayQrPayBean aliPayQrPayBean = JSON.parseObject(str, new TypeReference<AliPayQrPayBean>() {
                });
                //调取支付宝扫码支付接口成功，得到二维码，打印--顾客扫码支付--收到成功回调，后台写个回调成功地址
                break;
            case Contants.WXPAY_CODE:
                WxPayBean wxPayBean = JSON.parseObject(str, new TypeReference<WxPayBean>() {
                });
                Toasts.show(context, wxPayBean.getReturn_msg());
                break;
            case Contants.WXQRPAY_CODE:
                WxQrPayBean wxQrPayBean = JSON.parseObject(str, new TypeReference<WxQrPayBean>() {
                });
                //调取支付宝扫码支付接口成功，得到二维码，打印--顾客扫码支付--收到成功回调，后台写个回调成功地址

                break;
        }
    }

    @Override
    public void onAlert(int requestCode, String str) {

    }

    @Override
    public void onFailure(int requestCode, String str) {
        Log.d("ABOUT PAY=====onFailure", str);
        switch (requestCode) {
            case Contants.ALIPAY_FACEPAY_CODE:
                AliPayFacePayBean aliPayFacePayBean = JSON.parseObject(str, new TypeReference<AliPayFacePayBean>() {
                });
                Toasts.show(context, aliPayFacePayBean.getMsg());
                break;
            case Contants.ALIPAY_QRPAY_CODE:
                AliPayQrPayBean aliPayQrPayBean = JSON.parseObject(str, new TypeReference<AliPayQrPayBean>() {
                });
                Toasts.show(context, aliPayQrPayBean.getMsg());
                break;
            case Contants.WXPAY_CODE:
                WxPayBean wxPayBean = JSON.parseObject(str, new TypeReference<WxPayBean>() {//确认返回成功返回字段
                });
                Toasts.show(context, wxPayBean.getReturn_msg());
                break;
            case Contants.WXQRPAY_CODE:
                WxQrPayBean wxQrPayBean = JSON.parseObject(str, new TypeReference<WxQrPayBean>() {
                });
                if (wxQrPayBean.getCode_url() == null) {
                    Toasts.show(context, "创建二维码失败");
                }
                break;
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        unbindDeviceService();
    }
}
